﻿using UnityEngine;

namespace Core
{
    public class MoveComponent : Entity, IAwake, IFixedUpdate
    {
        private float rotateSpeed;
        private float moveSpeed;
        private float speed;
        private Vector3 direction;
        private Quaternion targetDirection;
        private Unit unit;
        private NumericComponent numericComponent;
        private StateMachineComponent stateMachineComponent;

        void IAwake.Awake()
        {
            unit = GetParent<Unit>();
            numericComponent = unit.GetComponent<NumericComponent>();
            stateMachineComponent = unit.GetComponent<StateMachineComponent>();
        }

        public void SetDirection(Vector3 direction)
        {
            this.direction = direction;
        }

        public void SetSpeed(float speed)
        {
            this.speed = speed;
        }

        void IFixedUpdate.FixedUpdate()
        {
            if (stateMachineComponent.State != StateType.Move)
                return;

            Rotation();
            Move();
        }

        void Move()
        {
            moveSpeed = numericComponent.GetAsFloat(NumericType.moveSpeed);
            // speed 输入的移动速度
            // moveSpeed 定义的移动速度
            // 单位向前移动
            unit.transform.Translate(unit.transform.forward * speed * moveSpeed * Time.deltaTime, Space.World);
        }

        void Rotation()
        {
            if (direction == Vector3.zero)
                return;

            //旋转单位至目标方向
            targetDirection = Quaternion.LookRotation(direction, Vector3.up);
            rotateSpeed = numericComponent.GetAsFloat(NumericType.rotateSpeed);
            unit.transform.rotation = Quaternion.Slerp(unit.transform.rotation, targetDirection, Time.deltaTime * rotateSpeed);
        }
    }
}